package com.ruoyi.process.pipemaintainence.controller;

import com.ruoyi.common.entity.APIResult;
import com.ruoyi.common.enums.StateEnum;
import com.ruoyi.common.id.IdGenerator;
import com.ruoyi.common.utils.BeanUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.process.pipemaintainence.domain.DrainagePipeMaintainence;
import com.ruoyi.process.pipemaintainence.service.BpmnApprovalService;
import com.ruoyi.process.pipemaintainence.service.BpmnCopyProcessService;
import com.ruoyi.process.pipemaintainence.service.IDrainagePipeMainService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;

import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Api(tags = "管养控制器", value = "管养控制器")
@RestController
@RequestMapping("/bpmn/drainagePipe")
public class DrainagePipeMainController {

    protected static final Logger logger = LoggerFactory.getLogger(DrainagePipeMainController.class);

    @Autowired
    protected IDrainagePipeMainService drainagePipeMainService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    protected IdGenerator idGenerator;

    @Autowired
    protected BpmnCopyProcessService processService;

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    protected HistoryService historyService;

    @Autowired
    protected ISysUserService userService;

    @Autowired
    protected BpmnApprovalService bpmnApprovalService;

    @Autowired
    protected BpmnCopyProcessService bpmnCopyProcessService;


    /**
     * 启动管养审批流程
     *
     * @param drainagePipeMaintainence 管养业务实体
     * @param processDefinitionId      流程定义id
     * @param userId                   启动流程用户id
     * @return
     */
    @ApiOperation(value = "启动管养审批流程", notes = "启动管养审批流程")
    @RequestMapping(value = "/start/{processDefinitionId}", method = RequestMethod.POST)
    public APIResult startWorkflow(@RequestBody DrainagePipeMaintainence drainagePipeMaintainence,
                                   @PathVariable("processDefinitionId") String processDefinitionId, String userId) {
        APIResult result = new APIResult<>();
        ProcessInstance processInstance = null;
        logger.info("com.tc.biz.controller.DrainagePipeMainController.startWorkflow()--->processDefinitionId: {},userId:{} ", processDefinitionId, userId);
        try {
            //TODO
            if (BeanUtils.isEmpty(userId)) {
                //获取当前登录用户
                SysUser user = ShiroUtils.getSysUser();
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            //启动流程实例，返回流程实例
            processInstance = drainagePipeMainService.start(drainagePipeMaintainence, userId, processDefinitionId);
            result.setCause(processInstance.getId());
            result.setMessage("流程启动成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/drainagePipe/start/" + processDefinitionId, e);
        }
        return result;
    }


    /**
     * 通过任务id查询任务详情数据
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "通过任务id查询任务详情数据", notes = "通过任务id查询任务详情数据")
    @RequestMapping(value = "/processInstance/running/detail", method = RequestMethod.POST)
    public APIResult<DrainagePipeMaintainence> findRunningProcessInstanceDetail(@RequestBody HashMap<String, Object> map) {
        APIResult<DrainagePipeMaintainence> result = new APIResult<>();
        String taskId = (String) map.get("taskId");
        String status = (String) map.get("status");
        if (!status.equals("todo") && !status.equals("complete"))
            throw new RuntimeException("status is must todo or complete");
        if (BeanUtils.isEmpty(taskId)) throw new RuntimeException("taskId is should not null");
        try {
            DrainagePipeMaintainence drainagePipeMaintainence = drainagePipeMainService.findRunningProcessInstanceDetail(taskId, status);
            result.setData(drainagePipeMaintainence);
            result.setMessage("查询任务详情数据成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/drainagePipe/processInstance/running/detail", e);
        }
        return result;
    }


    /**
     * 通过流程实例id查询详情数据
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "通过流程实例id查询详情数据", notes = "通过流程实例id查询详情数据")
    @RequestMapping(value = "/processInstance/detail", method = RequestMethod.POST)
    public APIResult<DrainagePipeMaintainence> findDetailByProcessInstanceId(@RequestBody HashMap<String, Object> map) {
        APIResult<DrainagePipeMaintainence> result = new APIResult<>();
        String processInstanceId = (String) map.get("processInstanceId");
        try {
            DrainagePipeMaintainence drainagePipeMaintainence = drainagePipeMainService.findByProcessInstanceId(processInstanceId);
            result.setData(drainagePipeMaintainence);
            result.setMessage("查询任务详情数据成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/drainagePipe/processInstance/detail", e);
        }
        return result;
    }


    /**
     * 办理任务
     * @param map
     * @param request
     * @return
     */
    @ApiOperation(value = "通过任务id完成任务", notes = "通过任务id完成任务")
    @RequestMapping(value = "/complete", method = RequestMethod.POST)
    public APIResult complete(@RequestBody HashMap<String, Object> map, HttpServletRequest request) {
        APIResult result = new APIResult<>();
        String userId = (String) map.get("userId"); //  办理用户id
        String taskId = (String) map.get("taskId"); // 任务id
        Boolean opinion = (Boolean) map.get("opinion"); // 意见
        if (BeanUtils.isEmpty(opinion)) throw new RuntimeException("审批意见不能为空");
        if (BeanUtils.isEmpty(taskId)) throw new RuntimeException("taskId不能为空");
        String comment = (String) map.get("comment");
        try {
            //TODO
            if (BeanUtils.isEmpty(userId)) {
                //获取当前登录用户
                SysUser user = ShiroUtils.getSysUser();
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            drainagePipeMainService.completeTask(userId, taskId, opinion, comment);
            result.setMessage("任务办理成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/drainagePipe/processInstance/running/detail", e);
        }
        return result;
    }


    /**
     * 根据任务id返回流程实例对应所有的 批注信息
     *
     * @param taskId 任务信息
     * @return 批注信息
     */
    public List<Comment> getProcessComments(String taskId) {
        List<Comment> historyCommnets = new ArrayList<>();
        // 1) 获取流程实例的ID
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        //2）通过流程实例查询所有的(用户任务类型)历史活动
        List<HistoricActivityInstance> hais = historyService.createHistoricActivityInstanceQuery().processInstanceId(pi.getId()).activityType("userTask").list();
        //3）查询每个历史任务的批注
        for (HistoricActivityInstance hai : hais) {
            String historytaskId = hai.getTaskId();
            List<Comment> comments = taskService.getTaskComments(historytaskId);
            // 4）如果当前任务有批注信息，添加到集合中
            if (comments != null && comments.size() > 0) {
                historyCommnets.addAll(comments);
            }
        }
        //5）返回
        return historyCommnets;
    }

}


